package com.ruoyi.common.redisTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisCallback;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class RedisKeepAliveTask {

    @Autowired
    private RedisTemplate redisTemplate;

//    // 通过构造器注入 RedisTemplate
//    public RedisKeepAliveTask(RedisTemplate<String, Object> redisTemplate) {
//        this.redisTemplate = redisTemplate;
//    }

    // 每隔 60 秒执行一次
    @Scheduled(fixedRate = 6000) // 60000ms = 60s
    public void keepAlive() {
        System.out.println("redis 心跳");
        try {
            String response = (String) redisTemplate.execute(
                    (RedisCallback<String>) connection -> connection.ping()
            );
            // 正常情况会返回 "PONG"
             System.out.println("Redis PING 响应: " + response); // 可选：打印日志
        } catch (Exception e) {
            // 捕获异常，记录 Redis 连接可能出了问题
            System.err.println("Redis 连接异常，PING 失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}